import { Injectable, Logger } from '@nestjs/common'
import { InjectEntityManager, InjectRepository } from '@nestjs/typeorm'
import Redis from 'ioredis'

import { isNil } from 'lodash'

import { EntityManager, Like, Repository } from 'typeorm'

import { InjectRedis } from '~/common/decorators/inject-redis.decorator'

import { paginate } from '~/helper/paginate'
import { Pagination } from '~/helper/paginate/pagination'
import { UserAlarmDto, UserAlarmQueryDto, UserAlarmUpdateDto } from './userAlarm.dto'
import { UserAlarmEntity } from './userAlarm.entity'

@Injectable()
export class UserAlarmService {
  private logger = new Logger(UserAlarmService.name)

  constructor(
    @InjectRedis() private readonly redis: Redis,
    @InjectRepository(UserAlarmEntity)
    private userAlarmRepository: Repository<UserAlarmEntity>,
    @InjectEntityManager() private entityManager: EntityManager,
  ) { }

  /**
   * 告警查询
   * @param queryDto
   */
  async listAlarm(queryDto: UserAlarmQueryDto): Promise<Pagination<UserAlarmEntity>> {
    const { page, pageSize, userId, uid, type, content, status, deptId } = queryDto
    const queryBuilder = await this.userAlarmRepository
      .createQueryBuilder('data')
      .leftJoinAndSelect('data.user', 'user')
      .select(['data.id', 'data.userId', 'data.uid', 'data.type', 'data.content', 'data.status', 'data.startAt', 'data.endAt', 'user.deptId', 'user.nickname'])
      .where({
        ...((!isNil(type) && type > 0) && { type }),
        ...((!isNil(status) && status > 0) && { status }),
        ...(uid && { uid }),
        ...(content && { content: Like(`%${content}%`) }),
        user: {
          ...(userId && { id: userId }),
          ...(deptId && { deptId }),
        },
      })
      // .andWhere({
      //   ...((time && time[0]) && { startAt: MoreThanOrEqual(time[0]) }),
      // })
      // .andWhere({
      //   ...((time && time[1]) && { startAt: LessThanOrEqual(time[1]) }),
      // })
      .orderBy('data.startAt', 'DESC')
    // this.logger.debug('queryBuilder', queryBuilder.getQueryAndParameters())
    return paginate<UserAlarmEntity>(queryBuilder, {
      page,
      pageSize,
    })
  }

  /**
   * 告警保存
   * @param data
   */
  async saveAlarm(data: UserAlarmDto) {
    return this.userAlarmRepository.save(data)
  }

  /**
   * 告警保存
   * @param id
   * @param data
   */
  async updateAlarm(id: number, data: UserAlarmUpdateDto) {
    return this.userAlarmRepository.update(id, data)
  }

  /**
   * 告警删除
   * @param id
   */
  async deleteAlarm(id: number) {
    return this.userAlarmRepository.delete(id)
  }
}
